﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;
using System.Globalization;
using Microsoft.Search.Interop;
using System.Data.OleDb;
using ClipShow2.Storage;
using ClipShow2.MediaTypes;

namespace ClipShow2.MediaFinder
{
    public class SearchEngine
    {
        public SearchEngine()
        {
        }
        private const string WDS_SEARCH_COLUMNS = "\"System.ItemUrl\",\"System.Media.Duration\",\"System.ItemDate\",\"System.Title\",\"System.Comment\",\"System.Author\",\"System.Media.SubTitle\",\"System.ParentalRating\"";
        private static OleDbConnection _connection;
        private static OleDbDataReader ExecuteReader(string query)
        {
            string connectionString = "Provider=Search.CollatorDSO;Extended Properties='Application=Windows';";
            _connection = new OleDbConnection(connectionString);
            _connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = _connection;
            command.CommandText = query;
            OleDbDataReader reader = command.ExecuteReader();
            return reader;
        }

        private static ClipShowMetadata ExtractFromWDS(string sourceFilePath, OleDbDataReader reader)
        {
            ClipShowMetadata mt = new ClipShowMetadata();
            mt.Url = sourceFilePath;

            try
            {
                Decimal duration = (Decimal)reader.GetValue(1);
                mt.Duration = Convert.ToInt64(duration) / 10000;
            }
            catch
            {
                mt.Duration = -1;
            }
            mt.CreationDateTime = (DateTime)reader.GetValue(2);

            try
            {
                mt.Title = (string)reader.GetValue(3);
            }
            catch
            {
                mt.Title = Path.GetFileNameWithoutExtension(sourceFilePath);
            }

            try
            {
                mt.Description = (string)reader.GetValue(4);
            }
            catch
            {
                mt.Description = "";
            }

            try
            {
                mt.Author = (string)reader.GetValue(5);
            }
            catch
            {
                mt.Author = "";
            }

            try
            {
                mt.ParentalRating = (string)reader.GetValue(7);
            }
            catch
            {
                mt.ParentalRating = "unrated content";
            }

            string[] temp = mt.Url.Split('\\');
            string hashedFile = Path.GetDirectoryName(mt.Url).Replace(@"\", "_");

            string targetFile = String.Format("{0}\\{1}_{2}.jpg",
                StorageEngine.GetThumbnailDir(),
                hashedFile.Replace(":", "_"),
                Path.GetFileNameWithoutExtension(mt.Url));

            mt.ThumbnailUrl = targetFile;
            return (mt);
        }

        public static ClipShowContent SearchLocalCatalog(string searchStr)
        {
            ClipShowContent rootCm = new ClipShowContent();
            try
            {
                // Use Windows Search to find our local media
                CSearchManager manager = new CSearchManagerClass();
                CSearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");
                CSearchQueryHelper queryHelper = catalogManager.GetQueryHelper();
                rootCm.ContentSourceName = String.Format("Search Term:{0}", searchStr);
                queryHelper.QuerySelectColumns = WDS_SEARCH_COLUMNS;
                string query = queryHelper.GenerateSQLFromUserQuery(
                    String.Format("{0} kind:videos store:file",searchStr));

                OleDbDataReader reader = ExecuteReader(query);
                while (reader.Read())
                {
                    Uri convert = new Uri(reader.GetString(0));
                    if (!Path.GetExtension(convert.LocalPath).Equals(".asx"))
                    {
                        if (File.Exists(convert.LocalPath))
                        {
                            ClipShowMetadata item = ExtractFromWDS(convert.LocalPath, reader);
                            rootCm.MediaItems.Add(item);
                        }
                    }
                }
                reader.Close();
            }
            catch
            {

            }
            return (rootCm);

        }

        public static ClipShowContent SearchLocalCatalogAll(string contentSourceName)
        {
            ClipShowContent rootCm = new ClipShowContent();
            try
            {
                // Use Windows Search to find our local media
                CSearchManager manager = new CSearchManagerClass();
                CSearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");
                CSearchQueryHelper queryHelper = catalogManager.GetQueryHelper();
                rootCm.ContentSourceName = contentSourceName;
                queryHelper.QuerySelectColumns = WDS_SEARCH_COLUMNS;
                string query = queryHelper.GenerateSQLFromUserQuery("* kind:videos store:file");

                OleDbDataReader reader = ExecuteReader(query);
                while (reader.Read())
                {
                    Uri convert = new Uri(reader.GetString(0));
                    if (!Path.GetExtension(convert.LocalPath).Equals(".asx"))
                    {
                        if (File.Exists(convert.LocalPath))
                        {
                            ClipShowMetadata item = ExtractFromWDS(convert.LocalPath, reader);
                            rootCm.MediaItems.Add(item);
                        }
                    }
                }
                reader.Close();
            }
            catch(SystemException se) 
            {
                Console.WriteLine(se.Message);
            }
            return (rootCm);

        }
    }
}
